<!--
 * @Author: t-xiangqun.li t-xiangqun.li@pcitc.com
 * @Date: 2025-10-20 15:53:06
 * @LastEditors: lixiangqun
 * @LastEditTime: 2025-11-16 18:12:54
 * @FilePath: \electrconVue\src\components\MessageInput.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div
    class="message-input bg-white border p-1 border-gray-300 rounded-md justify-between w-full focus-within:border-green-700"
    :class="{ 'bg-gray-50': disabled }"
  >
    <div v-if="imagePreview">
      <img :src="imagePreview" alt="preview" class="w-24 border-r-2" />
    </div>
    <div class="flex items-center">
      <input
        type="file"
        accept="image/*"
        ref="fileInput"
        class="hidden"
        @change="handleUploadFile"
      />
      <span
        :class="[
          'mr-2',
          disabled ? 'disabled:cursor-not-allowed' : 'cursor-pointer',
        ]"
        @click="triggerFileInput"
        >图片</span
      >
      <input
        type="text"
        class="flex-1 outline-none"
        :class="{ 'disabled:cursor-not-allowed': disabled }"
        v-model="model"
        :disabled="disabled"
      />
      <button
        class="bg-green-700 border cursor-pointer border-green-700 text-white shadow-sm rounded-[4px] inline-flex items-center justify-center h-[32px] px-[15px] py-[8px] text-sm hover:bg-green-700/90 disabled:cursor-not-allowed disabled:bg-green-700/90"
        :disabled="disabled"
        @click="onCreate"
      >
        <i class="mr-[2px]">→</i>发送
      </button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { defineModel, ref } from "vue";
const model = defineModel<string>("inputValue");
const props = defineProps<{ disabled?: boolean }>();
const emit = defineEmits<{ create: [value: string, imagePath?: string] }>();
const fileInput = ref<HTMLInputElement | null>(null);
const imagePreview = ref<string>();
const triggerFileInput = () => {
  if (!props.disabled) {
    fileInput.value?.click();
  }
};
let selectedImage: File | null = null;
const handleUploadFile = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    selectedImage = target.files[0];
    const reader: FileReader = new FileReader();
    reader.onload = (e) => {
      imagePreview.value = e.target?.result as string;
      console.log(selectedImage);
    };
    reader.readAsDataURL(selectedImage);
  }
};
const onCreate = () => {
  if (model.value && model.value.trim() !== "") {
    let filePath: string | undefined;
    if (selectedImage) {
      filePath = window.electronAPI.getFilePath(selectedImage as File);
    }
    emit("create", model.value, filePath || undefined);
    selectedImage = null;
    imagePreview.value = "";
  }
};
</script>
